package com.zxy.car.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zxy.car.config.GuliESConfig;
import com.zxy.car.entity.BuycarEntity;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxy.common.utils.PageUtils;
import com.zxy.common.utils.Query;

import com.zxy.car.dao.RecordDao;
import com.zxy.car.entity.RecordEntity;
import com.zxy.car.service.RecordService;


@Service("recordService")
public class RecordServiceImpl extends ServiceImpl<RecordDao, RecordEntity> implements RecordService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageUtils queryPage1(Map<String, Object> params) {
        QueryWrapper<RecordEntity> wrapper = new QueryWrapper<>();

        String key1 = (String) params.get("key1");
        String key2 = (String) params.get("key2");
        String key3 = (String) params.get("key3");
        String key4 = (String) params.get("key4");


        if (StringUtils.isNotEmpty(key1)){
            wrapper.and(w->{
                w.gt("buymoney",key1);
            });
        }
        if (StringUtils.isNotEmpty(key2)){
            wrapper.and(w->{
                w.lt("buymoney",key2);
            });
        }
        if (StringUtils.isNotEmpty(key3)){
            wrapper.and(w->{
                w.gt("addway",key3);
            });
        }
        if (StringUtils.isNotEmpty(key4)){
            wrapper.and(w->{
                w.lt("addway",key4);
            });
        }

        IPage<RecordEntity> page = this.page(
                new Query<RecordEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        try{
            List<RecordEntity> list = baseMapper.selectList(null);

            BulkRequest bulkRequest = new BulkRequest();
            for(RecordEntity recordEntity : list) {
                IndexRequest indexRequest = new IndexRequest("payrecord");
                indexRequest.id(recordEntity.getId().toString());
                String jsonString = JSONObject.toJSONString(recordEntity);
                indexRequest.source(jsonString, XContentType.JSON);
                bulkRequest.add(indexRequest);
            }

            BulkResponse bulk = client.bulk(bulkRequest, GuliESConfig.COMMON_OPTIONS);
            //再查询
            SearchRequest searchRequest = new SearchRequest("payrecord");
            //查询条件
            String key1 = (String) params.get("buymoney");
            String key2 = (String) params.get("buymoney");
            String key3 = (String) params.get("addway");
            String key4 = (String) params.get("addway");
            String page = (String) params.get("page");
            String limit = (String) params.get("limit");


            //构建条件
            SearchSourceBuilder builder = new SearchSourceBuilder();
            //分页
            builder.from((Integer.valueOf(page)-1)*Integer.valueOf(limit));
            builder.size(Integer.valueOf(limit));
            //模糊条件
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();


            builder.query(boolQueryBuilder);
            //条件封装
            SearchRequest source = searchRequest.source(builder);
            System.out.println("条件:"+source);
            //执行
            SearchResponse resp = client.search(searchRequest, GuliESConfig.COMMON_OPTIONS);
            System.out.println("结果:"+resp);
            Long total = resp.getHits().getTotalHits().value;
            SearchHit[] hits = resp.getHits().getHits();
            List<RecordEntity> collect = Arrays.stream(hits).map(h -> {
                RecordEntity recordEntity = JSONObject.parseObject(h.getSourceAsString(),RecordEntity.class);
                return recordEntity;
            }).collect(Collectors.toList());
            return new PageUtils(collect,total.intValue(),Integer.valueOf(limit),Integer.valueOf(page));
        }catch (Exception e){
            e.printStackTrace();
        }
        return  null;
    }


    @Override
    public void addRecord(String loginName, Double buymoney, Integer plan, Double monthpay, Double naotherpay, Double sum) {
        RecordEntity recordEntity = new RecordEntity();
        recordEntity.setBuytime(new Date());
        recordEntity.setPlan(plan);
        recordEntity.setBuymoney(buymoney);
        recordEntity.setStatus(0);
        recordEntity.setPaybackmoney(0.0);
        recordEntity.setLosepackbackmoney(sum);
        recordEntity.setAddress("申请中");
        recordEntity.setPayadd(naotherpay);
        Integer a = new Date().getMonth();
        if (a>=19){
            recordEntity.setRecentpayback(new Date().getYear()+"-"+new Date().getMonth()+1+"-"+new Date().getDay());
        }else {
            recordEntity.setRecentpayback("2022-04-19");
        }
        if (buymoney<200000){
            recordEntity.setAddway("2%");
        }else if (200000<=buymoney&&buymoney<500000){
            recordEntity.setAddway("4%");
        }else if (500000<=buymoney&&buymoney<800000){
            recordEntity.setAddway("5%");
        }else if (800000<=buymoney&&buymoney<1000000){
            recordEntity.setAddway("6%");
        }else if (buymoney>=1000000){
            recordEntity.setAddway("9%");
        }
        baseMapper.insert(recordEntity);
        System.out.println("生成成功，短信已发送");
    }

    @Override
    public void updaterecord(Integer id,String loginName) {
        RecordEntity recordEntity = baseMapper.selectById(id);
        recordEntity.setStatus(1);
        recordEntity.setAddress(loginName);
        baseMapper.updateById(recordEntity);
        System.out.println("已抢单短信已发送至用户");
    }

}